package com.rtx.api.interceptor;

import com.alibaba.fastjson.JSON;
import com.rtx.api.bean.ApiResponse;
import com.rtx.api.utils.JwtUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if("OPTIONS".equals(request.getMethod())){
            return true;
        }
        try {
            String token = request.getHeader(HttpHeaders.AUTHORIZATION);
            JwtUtils.getTokenClaim(token.replace("Bearer ",""));
            return true;
        } catch (Exception e) {
            logger.error("token验证异常",e);
            response.setStatus(401);
            ApiResponse r = ApiResponse.failed().code(401).msg("token验证失败");
            response.setContentType("application/Json; charset=UTF-8");
            response.getWriter().print(JSON.toJSON(r));
        }
        return false;
    }
}
